package com.zlx.guguanjia.Interceptor;

import com.zlx.guguanjia.entity.SysResource;
import com.zlx.guguanjia.service.SysResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author 周罗校
 * @Description 用户访问资源权限拦截处理
 * @ClassName ResourceInteceptor
 * @date 2020.11.06 16:08:41
 * 该版权归周罗校所有，最终解释权以官方为准
 */

@Component
public class ResourceInteceptor implements HandlerInterceptor {
    @Autowired
    private SysResourceService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取需要权限鉴定的地址
        List<SysResource> sysResources = service.selectResource();
        //获取进行拦截的地址
        String uri = request.getRequestURI();
        uri=uri.replace(request.getContextPath()+"/","");
        //是否需要鉴权的标识
        boolean need = false;
        for (SysResource sysResource : sysResources) {
            if (uri.equals(sysResource.getUrl())){
                //需要鉴权
                need=true;
                break;
            }
        }
        if (need){
            List<SysResource> resources = (List<SysResource>) request.getSession().getAttribute("resources");
            for (SysResource resource : resources) {
                if (uri.equals(resource.getUrl())){
                    //用户具有权限放行
                    return true;
                }
            }
            //用户无权限访问，拦截
            response.sendRedirect(request.getContextPath()+"/notauth.html");
            return false;
        }
        //无需鉴权直接放行
        return true;
    }
}
